var gulp = require('gulp'),
    //压缩js文件
    uglify = require('gulp-uglify'),
    //重命名文件
    rename = require('gulp-rename'),
    //压缩css文件
    cssnano = require('gulp-cssnano'),
    //less文件
    less = require('gulp-less'),
    //自动补全浏览器前缀
    autoprefixer = require('gulp-autoprefixer'),
    //压缩html
    htmlmin = require('gulp-htmlmin'),
    //压缩图片
    imagemin = require('gulp-imagemin'),
    //合并文件
    concat = require('gulp-concat'),
    //项目清理
    clean = require('gulp-clean'),
    //热更新
    connect = require('gulp-connect'),
    //网站服务
    webserver = require('gulp-webserver');

//js资源路径
var jsSrc = 'src/js/*.js';
var jsDist = 'dist/js';

//css资源路径
var cssSrc = 'src/css/*.css';
var cssDist = 'dist/css';

//图片资源路径
var imgSrc = 'src/images/*';
var imgDist = 'dist/images';

//第三方资源路径
var vendorSrc = 'src/vendor/**/*';
var vendorDist = 'dist/vendor';

//html资源路径
var htmlSrc = 'src/*.html';
var htmlDist = 'dist';

//压缩js
gulp.task('js', function(){
  return gulp.src(jsSrc)
    .pipe(uglify())
    .pipe(gulp.dest(jsDist))
    .pipe(connect.reload());
});

// 合并并压缩css
gulp.task('css', function(){
  return gulp.src(cssSrc)
    .pipe(less())
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(cssnano())
    .pipe(gulp.dest(cssDist))
    .pipe(connect.reload());
});

//压缩图片
gulp.task('img', function(){
  return  gulp.src(imgSrc)
    .pipe(imagemin())
    .pipe(gulp.dest(imgDist))
    .pipe(connect.reload());
});

//引入第三方资源
gulp.task('vendor', function(){
  return  gulp.src(vendorSrc)
    .pipe(gulp.dest(vendorDist));
});

// 合并并压缩html
gulp.task('html', function(){
  return gulp.src(htmlSrc)
    .pipe(htmlmin())
    .pipe(gulp.dest(htmlDist))
    .pipe(connect.reload());
});

//定义livereload任务
gulp.task('connect', function () {
    connect.server({
        livereload: true
    });
});

//定义看守任务
gulp.task('watch', function () {
    gulp.watch(jsDist, ['js']);
    gulp.watch(cssDist, ['css']);
    gulp.watch(htmlSrc, ['html']);
});

//启动服务
gulp.task('webserver', function() {
  gulp.src('./')
    .pipe(webserver({
        port:8080,
        livereload: true,
        directoryListing: true,
        open: true
    }));
});

//目标目录清理
gulp.task('clean', function() {
  gulp.src(['dist'], {read: false})
    .pipe(clean());
});

//项目开始
gulp.task('start', ['js', 'css', 'html', 'img', 'vendor', 'watch', 'webserver']);
//构建
gulp.task('build', ['js', 'css', 'html', 'img','vendor']);
